<?php


namespace App\Http\Controllers\Api;

use App\Businesses\BusinessState;
use App\Http\Requests\ApiV2\WeightFragmentRequest;
use App\Services\Base\Interfaces\ConfigServiceInterface;
use App\Services\Business\Models\WeightFragment;
use App\Services\Business\Models\Conquer;
use App\Services\Business\Models\UserConquer;
use App\Services\Business\Models\UserImage;
use App\Services\Business\Interfaces\CommentServiceInterface;
use App\Services\Business\Interfaces\VideoServiceInterface;
use App\Services\Business\Models\Image;
use App\Services\Business\Models\MediaImage;
use App\Services\Business\Services\CommentService;
use App\Services\Member\Interfaces\SocialiteServiceInterface;
use App\Services\Member\Interfaces\UserServiceInterface;
use App\Services\Member\Models\Activity;
use App\Services\Member\Models\User;
use App\Services\Member\Services\SocialiteService;
use App\Services\Member\Services\UserService;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

class WeightFragmentController extends BaseController
{


    /**
     * @var CommentService
     */
    protected $commentService;
    /**
     * @var UserService
     */
    protected $userService;
    protected $businessState;

    /**
     * @var SocialiteService
     */
    protected $socialiteService;


    public function __construct(

        CommentServiceInterface   $commentService,
        UserServiceInterface      $userService,
        BusinessState             $businessState,
        SocialiteServiceInterface $socialiteService

    )
    {

        $this->commentService = $commentService;
        $this->userService = $userService;
        $this->businessState = $businessState;
        $this->socialiteService = $socialiteService;

    }

    public function index(Request $request)
    {


        $size = $request->input('size', 5);

        $activities = WeightFragment::query()
            ->with(['images', 'videos'])
            ->orderByDesc('created_at')
            ->paginate($size);

        //发布的人
        $users = User::query()
            ->whereIn('id', array_column($activities->items(), 'user_id'))
            ->select(['id', 'nick_name', 'avatar', 'mobile'])
            ->get()
            ->keyBy('id');
        return $this->successData(compact('activities', 'users'));

    }

    public function detail(Request $request, $id)
    {

        $fragment = WeightFragment::query()->with(['user','images','videos','thumbsups'])->where('id', $id)->firstOrFail();
        $isFollowed = false;
        $isThumbsuped = false;
        if ($this->check()) {
            $isFollowed = $this->userService->isFollowed($this->id(), $fragment->user_id);
            $isThumbsuped = $this->userService->isThumbsuped($this->id(), $id, WeightFragment::class);
        }
        return $this->successData(compact('fragment', 'isFollowed', 'isThumbsuped'));


    }

    public
    function store(WeightFragmentRequest $request, WeightFragment $fragment)
    {

        $userId = $this->id();
        $data = $request->filldata();
        if ($this->userService->isPublishedToday($data['conquer_id'], $userId)) {
               return  $this->error(__('今天已经有提交过'));
        }
        DB::transaction(function () use ($fragment, $data, $userId) {

            $fragment->fill($data)->save($data);
            $fragment->images()->createMany($data['images']);
            $fragment->videos()->attach($data['video_ids']);
            $fragment->activity()->save(new Activity(['user_id' => $userId]));
        });
        return $this->success(__('新增动态成功'));
    }


    public function edit($id)
    {
        $date = date('Y-m-d');

        // 查找指定ID的记录
        $fragment = WeightFragment::query()
            ->where('id', $id)
            ->first();

        if (!$fragment) {
            return $this->error(__('动态不存在'));
        }

        // 检查记录的创建日期是否是今天
        if ($fragment->created_at->format('Y-m-d') !== $date) {
            return $this->error(__('只能编辑今天发布的动态'));
        }

        // 获取包含图片和视频的记录
        $fragment = WeightFragment::query()
            ->with(['images', 'videos'])
            ->where('id', $fragment->id)
            ->first();

        return $this->successData(compact('fragment'));

    }


    public
    function update(WeightFragmentRequest $request, $id)
    {

        $data = $request->filldata();
        $fragment = WeightFragment::query()->where('id', $id)->first();
        DB::transaction(function () use ($fragment, $data) {

            $fragment->fill($data)->save($data);
            $fragment->images()->delete();
            $fragment->images()->createMany($data['images']);
            $fragment->videos()->sync($data['video_ids']);

        });
        return $this->success(__('更新动态成功'));
    }


    public
    function delete($id, ConfigServiceInterface $configService, VideoServiceInterface $videoService)
    {
        $fragment = WeightFragment::query()->where('id', $id)->first();

        DB::transaction(function () use ($fragment, $videoService, $configService) {

            //删除视频点播的图片
            if ($fragment->images->isNotEmpty()) {
                $fragment->images()->delete();
                $images = $fragment->images->flatMap(function ($image) {
                    return [$image->url, $image->small_url];
                })->toArray();
                Storage::disk('oss')->delete($images);
            }

            //删除阿里云的视频
            if ($fragment->videos->isNotEmpty()) {
                $fragment->videos()->detach();
                $fragment->videos()->delete();
                $videoService->deleteVideo(implode(',', $fragment->videos->pluck('aliyun_video_id')->toArray()), $configService);
            }
            //删除动态本身
            $fragment->delete();
        });

        return $this->success(__('动态删除成功'));
    }


    public function rankDaily(Request $request)
    {

        $userId = $this->id();
        $conquerId = $request->input('conquer_id');
        $size = $request->input('size', 20);
        $rank = 0;
        // 获取今天的开始和结束时间
        $today = Carbon::today()->toDateString(); // 获取今天的日期
        $conquer = Conquer::query()->where('id', $conquerId)->first();
        // 获取今天的所有用户及其分数，按照分数排序
        $activities = WeightFragment::query()
            ->with(['user'])
            ->select(['id', 'user_id', 'last_different_weight', 'total_different_weight'])
            ->whereDate('created_at', $today)
            ->orderBy('last_different_weight', 'desc')
            ->paginate($size);

        if (!empty($activities->items())) {
            $firstUser = UserConquer::query()->where('conquer_id', $conquerId)->where('user_id', $activities->items()[0]['user_id'])->first();
        } else {
            $firstUser = [];
        }

        $todayRank = WeightFragment::whereDate('created_at', $today)
            ->orderBy('last_different_weight', 'desc')
            ->get();


        $user = $todayRank->firstWhere('user_id', $userId);

        if ($user) {
            // 查找用户成绩在集合中的位置
            $rank = $todayRank->search(function ($record) use ($user) {
                    return $record->last_different_weight <= $user->last_different_weight;
                }) + 1;

        }
        $myTodayRank = WeightFragment::query()->where('user_id', $userId)->whereDate('created_at', $today)->first() ?? [];
        return $this->successData(compact('rank', 'conquer', 'firstUser', 'myTodayRank', 'activities'));
    }


    /**
     * 获取用户最后的体重
     * @param Request $request
     * @return JsonResponse
     */
    public function latest(Request $request)
    {

        $userId = $this->id();
        $conquerId = $request->input('conquer_id');
        $fragment = WeightFragment::query()
            ->with(['conquer_id'])
            ->when($conquerId, function ($query) use ($conquerId) {
                $query->where('conquer_id', $conquerId);
            })
            ->where('user_id', $userId)
            ->latest()
            ->first();
        if ($fragment) {

            $weight = $fragment->weight;
        } else {
            $conquer = UserConquer::query()
                ->where('conquer_id', $conquerId)
                ->where('user_id', $userId)->first();
            $weight = $conquer->weight;


        }
        return $this->successData(compact('weight'));

    }


    /**
     * 对比
     * @return JsonResponse
     */
    public function compare()
    {

        $images = UserImage::query()
            ->with(['image:url', 'activity'])
            ->where('user_id', $this->id())
            ->get();

        $toers = User::query()->select(['id', 'nick_name', 'avatar'])->whereIn('id', $images->pluck('to_id'))->get();
        $conquers = Conquer::query()->select(['id', 'title', 'weight'])->whereIn('id', $images->pluck('conquer_id'))->get();
        //分组对比的id
        $imagesByToId = $images->groupBy('to_id');
        //分组挑战的id
        $images = $imagesByToId->map(function ($group) {
            return $group->groupBy('conquer_id');
        });
        return $this->successData(compact('images', 'conquers', 'toers'));


    }





    /**
     * 加入对比
     * @param Request $request
     * @return JsonResponse
     */
    public function joinImageComparison(Request $request, $imageId)
    {
        $userId = $this->id();
        $conquerId = $request->input('conquer_id');
        $activityId = $request->input('activity_id');
        $toId = $request->input('to_id');
        UserImage::create([
            'conquer_id' => $conquerId,
            'image_id' => $imageId,
            'activity_id' => $activityId,
            'to_id' => $toId,
            'user_id' => $userId
        ]);
        return $this->success(__('加入对比成功'));


    }

    public function deleteImageComparison($id)
    {

        UserImage::query()->where('id', $id)->delete();

        return $this->success(__('删除对比成功'));

    }

    public function imagesByConquerAndDate(Request $request, $userId, $conquerId)
    {

        $date = $request->input('date');
        $page = (int)$request->input('page', 1);
        $size = (int)$request->input('size', 10);
        [
            'total' => $total,
            'list' => $list,
        ] = $this->userService->getUserImageByConquerAndDate($userId, $conquerId, $date, $page, $size);
        $activities = $this->paginator($list, $total, $page, $size);
        return $this->successData(compact('activities'));
    }


}
